from odoo import models, fields, api
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import logging
from odoo.exceptions import UserError

logger = logging.getLogger(__name__)

class Adjust(models.Model):
    _name = 'person.adjust'
    _description = 'Some one may change their choice'
    _rec_name = 'name'


    name = fields.Many2one('person.info', '姓名', required=True)


    reason = fields.Html('调动理由', required=True)

    group = fields.Many2one('group.info', '意向技术组', required=True, domain=lambda self: [('name', '!=', self.name.ability.name)])


    # @api.model
    # def _limit_group(self):
    #     domain = lambda self: [('group', '!=', self.name.ability)]
    #     return {
    #         'domain': {'group': domain}
    #     }

    @api.onchange('group')
    def _verify_group(self):
        # print(self.name.ability.name)
        # print(self.group.name)
        if self.group.name == self.name.ability.name:
            return {
                'warning': {
                    'title': "异常",
                    'message': "不能调动到自己所在组",
                },
            }

    project_leader_comment = fields.Html(
        '项目组长意见'
    )

    deputy_director_comment = fields.Html(
        '副总监意见',
    )

    chief_director_comment = fields.Html(
        '总监意见',
    )

    teacher_comment = fields.Html(
        '老师意见',
    )

    state = fields.Selection(
        [
            # 默认为0的情况下，会置 null 不知道是不是odoo本身的bug
            (-1, '编辑'),
            (6, '项目组长审批'),
            (5, '副总监审批审批'),
            (4, '总监审批'),
            (3, '老师审批'),
            (2, '通过'),
            (1, '失败'),
        ],
        string='状态', default=-1, readonly=True, copy=False, track_visibility='onchange'
    )

    current_user_is_group_user = fields.Boolean(
        compute="_compute_current_user"
    )

    current_user_is_group_leader = fields.Boolean(
        compute="_compute_current_user"
    )

    current_user_is_deputy_director = fields.Boolean(
        compute="_compute_current_user"
    )

    current_user_is_director = fields.Boolean(
        compute="_compute_current_user"
    )

    current_user_is_teacher = fields.Boolean(
        compute="_compute_current_user"
    )

    comment_group_leader_state = fields.Boolean(
        '组长评论是否显示',
        default=False
    )

    comment_deputy_director_state = fields.Boolean(
        '副总监评论是否显示',
        default=False
    )

    comment_director_state = fields.Boolean(
        '总监评论是否显示',
        default=False
    )
    comment_teacher_state = fields.Boolean(
        '老师评论是否显示',
        default=False
    )


    # 判断当前用户的身份
    @api.one
    def _compute_current_user(self):
        self.current_user_is_group_leader = self.user_has_groups('sugon_system.asset_group_leader')
        self.current_user_is_deputy_director = self.user_has_groups('sugon_system.asset_deputy_director')
        self.current_user_is_director = self.user_has_groups('sugon_system.asset_director')
        self.current_user_is_teacher = self.user_has_groups('sugon_system.asset_teacher')
        print(self.current_user_is_group_leader)    #测试用

    def button_group_user(self):
        group = self.env['person.info'].search([])
        users = group.search([('title_rule', 'like', '%组长%')])
        for user in users:
            Adjust.call_owner(self, user)  # 向组长发送邮件
        self.comment_group_leader_state = True
        return self.write({"state": 6})

    def button_group_leader(self):
        group = self.env['person.info'].search([])
        users = group.search([('title_rule', 'like', '%技术副总监%')])
        for user in users:
            Adjust.call_owner(self, user)  # 向技术副总监发送邮件
        self.comment_deputy_director_state = True
        return self.write({"state": 5})

    def button_deputy_director(self):
        group = self.env['person.info'].search([])
        users = group.search([('title_rule', 'like', '%技术总监%')])
        for user in users:
            Adjust.call_owner(self, user)  # 向技术总监发送邮件
        self.comment_director_state = True
        return self.write({"state": 4})

    def button_director(self):
        group = self.env['person.info'].search([])
        users = group.search([('title_rule', 'like', '%老师%')])
        for user in users:
            Adjust.call_owner(self, user)  # 向老师发送邮件
        self.comment_teacher_state = True
        return self.write({"state": 3})

    def button_teacher(self):
        self.name.ability = self.group
        return self.write({"state": 2})

    # def button_pass(self):
    #     self.write({"state": 2})
    #     # 修改人员
    #     self.name.ability = self.group

    def button_fail(self):
        return self.write({"state": 1})

    @api.onchange('group')
    def _onchange_group(self):
        old_group = self.name.ability
        if self.group == old_group:
            self.write({"group": False})
            return {
                'warning': {
                    'title': "调动提醒",
                    'message': "已在所申请技术组中！",
                }
            }

    @api.one
    def call_owner(self, user):
        sender = 'zilouis@qq.com'
        passwd = 'sovlbfcttwogbhhi'
        logger.info("Here is the email addr: %s", user.email)
        receivers = user.email  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
        mail_msg = """
                <!doctype html>
                <html>
                  <head>
                    <meta name="viewport" content="width=device-width">
                    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                  </head>
                  <body class="" style="background-color: #f6f6f6; font-family: sans-serif; -webkit-font-smoothing: antialiased; font-size: 14px; line-height: 1.4; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;">
                    <table border="0" cellpadding="0" cellspacing="0" class="body" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background-color: #f6f6f6;">
                      <tr>
                        <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td>
                        <td class="container" style="font-family: sans-serif; font-size: 14px; vertical-align: top; display: block; Margin: 0 auto; max-width: 580px; padding: 10px; width: 580px;">
                          <div class="content" style="box-sizing: border-box; display: block; Margin: 0 auto; max-width: 580px; padding: 10px;">

                            <!-- START CENTERED WHITE CONTAINER -->
                            <span class="preheader" style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;">This is preheader text. Some clients will show this text as a preview.</span>
                            <table class="main" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background: #ffffff; border-radius: 3px;">

                              <!-- START MAIN CONTENT AREA -->
                              <tr>
                                <td class="wrapper" style="font-family: sans-serif; font-size: 14px; vertical-align: top; box-sizing: border-box; padding: 20px;">
                                  <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;">
                                    <tr>
                                      <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">
                                        <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">尊敬的{owner_name},</p>
                                        <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">有新的人员调动申请，请尽快登录系统进行审核！</p>
                                        <table border="0" cellpadding="0" cellspacing="0" class="btn btn-primary" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; box-sizing: border-box;">
                                          <tbody>
                                            <tr>
                                              <td align="left" style="font-family: sans-serif; font-size: 14px; vertical-align: top; padding-bottom: 15px;">
                                                <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: auto;">
                                                  <tbody>
                                                    <tr>
                                                      <td style="font-family: sans-serif; font-size: 14px; vertical-align: top; background-color: #3498db; border-radius: 5px; text-align: center;"> <a href="http://admin.hubusugon.cn" target="_blank" style="display: inline-block; color: #ffffff; background-color: #3498db; border: solid 1px #3498db; border-radius: 5px; box-sizing: border-box; cursor: pointer; text-decoration: none; font-size: 14px; font-weight: bold; margin: 0; padding: 12px 25px; text-transform: capitalize; border-color: #3498db;">湖北大学瑞翼工坊内部管理系统</a> </td>
                                                    </tr>
                                                  </tbody>
                                                </table>
                                              </td>
                                            </tr>
                                          </tbody>
                                        </table>
                                        <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">祝您生活愉快！</p>
                                      </td>
                                    </tr>
                                  </table>
                                </td>
                              </tr>

                            <!-- END MAIN CONTENT AREA -->
                            </table>

                            <!-- START FOOTER -->
                            <div class="footer" style="clear: both; Margin-top: 10px; text-align: center; width: 100%;">
                              <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;">
                                <tr>
                                  <td class="content-block" style="font-family: sans-serif; vertical-align: top; padding-bottom: 10px; padding-top: 10px; font-size: 12px; color: #999999; text-align: center;">
                                    <span class="apple-link" style="color: #999999; font-size: 12px; text-align: center;">版权所有©湖北大学瑞翼工坊</span>
                                  </td>
                                </tr>

                              </table>
                            </div>
                            <!-- END FOOTER -->

                          <!-- END CENTERED WHITE CONTAINER -->
                          </div>
                        </td>
                        <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td>
                      </tr>
                    </table>
                  </body>
                </html>
            """.format(owner_name=user.name)
        message = MIMEText(mail_msg, 'html', 'utf-8')
        message['From'] = Header("湖北大学瑞翼工坊", 'utf-8')
        message['To'] = Header(user.email, 'utf-8')

        subject = '湖北大学瑞翼工坊'
        message['Subject'] = Header(subject, 'utf-8')

        try:
            smtpObj = smtplib.SMTP_SSL("smtp.qq.com", 465)
            smtpObj.login(sender, passwd)
            smtpObj.sendmail(sender, receivers, message.as_string())
            print("邮件发送成功")
        except Exception as e:
            raise UserError(('邮件未发送成为!原因如下:%s') % e)